<template>
  <div class="register-page">
    <div class="register-container">
      <!-- Header -->
      <div class="header">
        <van-nav-bar title="Create Account" left-text="Back" left-arrow @click-left="$router.back()" />
      </div>

      <!-- Register Form -->
      <van-form @submit="handleRegister" class="register-form">
        <div class="form-fields">
          <!-- Username Field -->
          <div class="field-group">
            <label class="field-label">Username</label>
            <van-field v-model="registerForm.username" name="username" placeholder="Choose a username" :rules="[
              { required: true, message: 'Username is required' },
              { validator: validateUsername, message: 'Username must be 3-20 characters, letters, numbers, underscores only' }
            ]" clearable class="custom-field" />
          </div>

          <!-- Email Field -->
          <div class="field-group">
            <label class="field-label">Email</label>
            <van-field v-model="registerForm.email" name="email" placeholder="Enter your email" :rules="[
              { required: true, message: 'Email is required' },
              { validator: validateEmail, message: 'Please enter a valid email' }
            ]" clearable class="custom-field" />
          </div>

          <!-- Password Field -->
          <div class="field-group">
            <label class="field-label">Password</label>
            <van-field v-model="registerForm.password" type="password" name="password" placeholder="Create a password"
              :rules="[
                { required: true, message: 'Password is required' },
                { validator: validatePasswordStrength, message: 'Password is too weak' }
              ]" clearable class="custom-field" @input="checkPasswordStrength" />

            <!-- Password Strength Indicator -->
            <div v-if="registerForm.password" class="password-strength">
              <div class="strength-bar">
                <div class="strength-fill" :class="passwordStrength.strength" :style="{ width: getStrengthWidth() }">
                </div>
              </div>
              <div class="strength-text">
                Password strength: {{ passwordStrength.strength }}
              </div>
              <ul v-if="passwordStrength.issues.length" class="strength-issues">
                <li v-for="issue in passwordStrength.issues" :key="issue">
                  {{ issue }}
                </li>
              </ul>
            </div>
          </div>

          <!-- Confirm Password Field -->
          <div class="field-group">
            <label class="field-label">Confirm Password</label>
            <van-field v-model="registerForm.password_confirmation" type="password" name="password_confirmation"
              placeholder="Confirm your password" :rules="[
                { required: true, message: 'Password confirmation is required' },
                { validator: validatePasswordMatch, message: 'Passwords do not match' }
              ]" clearable class="custom-field" />
          </div>
        </div>

        <!-- Terms and Conditions -->
        <div class="terms-section">
          <van-checkbox v-model="registerForm.agreeToTerms">
            I agree to the
            <a href="/terms" target="_blank">Terms of Service</a>
            and
            <a href="/privacy" target="_blank">Privacy Policy</a>
          </van-checkbox>
        </div>

        <!-- Register Button -->
        <div class="form-actions">
          <van-button round block type="primary" native-type="submit" :loading="loading"
            :disabled="!registerForm.agreeToTerms" class="register-btn">
            Create Account
          </van-button>
        </div>
      </van-form>

      <!-- Login Link -->
      <div class="login-link">
        <span>Already have an account? </span>
        <router-link to="/auth/login">Sign in</router-link>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { validateEmail, validateUsername, validatePassword, validatePasswordConfirmation } from '@/utils/validate'
import type { RegisterData } from '@/types/user'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)

const registerForm = reactive<RegisterData>({
  username: '',
  email: '',
  password: '',
  password_confirmation: '',
  agreeToTerms: false
})

const passwordStrength = ref({
  isValid: false,
  strength: 'weak' as 'weak' | 'medium' | 'strong',
  issues: [] as string[]
})

const checkPasswordStrength = () => {
  if (registerForm.password) {
    passwordStrength.value = validatePassword(registerForm.password)
  }
}

const getStrengthWidth = () => {
  switch (passwordStrength.value.strength) {
    case 'weak': return '33%'
    case 'medium': return '66%'
    case 'strong': return '100%'
    default: return '0%'
  }
}

const validatePasswordStrength = (value: string) => {
  const result = validatePassword(value)
  return result.isValid
}

const validatePasswordMatch = (value: string) => {
  return validatePasswordConfirmation(registerForm.password, value)
}

const handleRegister = async () => {
  if (!registerForm.agreeToTerms) {
    showToast('Please agree to the Terms of Service and Privacy Policy')
    return
  }

  try {
    loading.value = true
    await userStore.register(registerForm)

    showToast({
      type: 'success',
      message: 'Account created successfully'
    })

    // Redirect to email verification or home page
    router.push('/auth/email-verification')

  } catch (error: any) {
    showToast({
      type: 'fail',
      message: error.message || 'Registration failed'
    })
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.register-page {
  min-height: 100vh;
  background: $background-color;
}

.register-container {
  max-width: 400px;
  margin: 0 auto;
  background: $white;
  min-height: 100vh;
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  background: $white;
  border-bottom: 1px solid $border-color;
}

.register-form {
  padding: $spacing-lg;
}

.form-fields {
  margin-bottom: $spacing-lg;

  .field-group {
    margin-bottom: $spacing-xl;

    .field-label {
      display: block;
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $text-color;
      margin-bottom: 8px;
    }

    .custom-field {
      :deep(.van-cell) {
        height: 46px;
        padding: 0 $spacing-md;
        background: $white;
        border: 2px solid $border-color;
        border-radius: $border-radius-md;
        box-shadow: none;
        display: flex;
        align-items: center;

        &:focus-within {
          border-color: $danger-color;
        }
      }

      :deep(.van-field__control) {
        height: 100%;
        font-size: $font-size-md;
        color: $text-color;
        line-height: 1;

        &::placeholder {
          color: $text-color-3;
        }
      }

      :deep(.van-field__label) {
        display: none;
      }

      :deep(.van-field__left-icon) {
        display: none;
      }

      :deep(.van-field__clear) {
        color: $text-color-3;
      }
    }
  }
}

.password-strength {
  margin-top: $spacing-sm;

  .strength-bar {
    height: 4px;
    background: $gray-3;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: $spacing-xs;

    .strength-fill {
      height: 100%;
      transition: width 0.3s ease;

      &.weak {
        background: $danger-color;
      }

      &.medium {
        background: $warning-color;
      }

      &.strong {
        background: $success-color;
      }
    }
  }

  .strength-text {
    font-size: $font-size-xs;
    color: $text-color-3;
    margin-bottom: $spacing-xs;
    text-transform: capitalize;
  }

  .strength-issues {
    font-size: $font-size-xs;
    color: $danger-color;
    margin: 0;
    padding-left: $spacing-md;

    li {
      margin-bottom: 2px;
    }
  }
}

.terms-section {
  margin: $spacing-lg 0;
  padding: 0 $spacing-md;

  a {
    color: $primary-color;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

.form-actions {
  margin: $spacing-lg 0;
  padding: 0 $spacing-md;

  .register-btn {
    height: 48px;
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;

    &:disabled {
      opacity: 0.5;
    }
  }
}

.login-link {
  text-align: center;
  padding: $spacing-lg;
  font-size: $font-size-sm;
  color: $text-color-3;

  a {
    color: $primary-color;
    text-decoration: none;
    font-weight: $font-weight-medium;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>